
import React from 'react'
import {Card,Row,Col,Button,Icon,Form, Input,message,Spin  } from 'antd';
import {Link} from 'react-router-dom'
import PureRenderMixin from 'react-addons-pure-render-mixin'

import LeftMenu from 'component/leftmenu/index.jsx';
import HeadImgContent from 'component/headimgcontent/index.jsx';
import LeftMenuItem from 'component/leftmenuitem/index.jsx';


import MMUtile from 'util/mm.jsx'
import Safty from 'service/safty-service.jsx'
import Verify from 'component/verify/index.jsx';
const _mm = new MMUtile();
const _safty = new Safty();


const FormItem = Form.Item;


let residences = [];	


let userInfo = _mm.getStorage('userInfo')?JSON.parse(_mm.getStorage('userInfo')):{};
class UpdateEmailForm extends React.Component{
	constructor(props){
		super(props);
		this.shouldComponentUpdate = PureRenderMixin.shouldComponentUpdate.bind(this);
		this.state = {
			loading:true,
			phone:'',
			email:'',
			isFirstPhone:true,
			isFirstEmail:true,
			isCheckPhoneOrEmail:false,
			items:[{'name':'修改密码','actived':false,'link':'/updatepsw','icon':'edit'},
			{'name':'密保设置','actived':false,'link':'/security','icon':'key'},
			{'name':'绑定手机','actived':false,'link':'/updatephone','icon':'mobile'},
			{'name':'登录邮箱','actived':true,'link':'','icon':'mail'},
			{'name':'登录记录','actived':false,'link':'/recordsafty','icon':'profile'}],
		}

	}
	componentWillMount(){
		
		
		//获取手机号
		_safty.getUserPhone().then((res)=>{
			if(res){
				this.setState({
					phone:res,
					isFirstPhone:false
				})
			}
		},(errMsg)=>{
			_mm.errorTips(errMsg)
		})

		//获取电子邮箱
		_safty.getEmail().then((res)=>{
			if(res){
				this.setState({
					email:res,
					isFirstEmail:false
				})
			}
			this.setState({
				loading:false
			})
		},(errMsg)=>{
			this.setState({
				loading:false
			})
			_mm.errorTips(errMsg)
		})
	}
	
	componentWillUpdate(){
		userInfo = _mm.getStorage('userInfo')?JSON.parse(_mm.getStorage('userInfo')):{};
	}
	handleSubmit(e){
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
    	if (err) {
        return;
      }
	    _safty.checkEmail({
				email:values.email
			}).then((res)=>{
				_safty.updateEmail({
					email:values.email
				}).then((res)=>{
					let sessionEmail = values.email.substr(0, 2)+"******@"+values.email.split('@')[1];
					userInfo.email = sessionEmail;
					_mm.setStorage('userInfo',userInfo);
					message.success('用户电子邮箱保存成功');
					this.props.history.push('/');
				},(errMsg)=>{
					_mm.errorTips(errMsg);
				})
			},(errMsg)=>{
				_mm.errorTips(errMsg);
			})
			
      
    });
  }
	checkEmail(rule, value, callback){
    const form = this.props.form;
    const email = form.getFieldValue('email')

    let reg = new RegExp("^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$"); 
    if(!reg.test(email)){ 
        callback("邮箱地址填写有误，请重填");  
    }  else {
    	
      callback();
    }
  }
	getIsCodeRight(callback){
		this.setState({
			isCheckPhoneOrEmail:callback.isCodeRight,
			email:''
		})
	}
	render(){
		const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 14 },
      },
    };
		return(
			<div>
				<Row gutter={24}>
					<Col span={7}>
		        <Card bordered={true} className="itemminheight"><LeftMenuItem items={this.state.items}></LeftMenuItem></Card>
		      </Col>
		      <Col span={17}>
						<Spin spinning={this.state.loading}   size="large">
						{
							!this.state.isCheckPhoneOrEmail
							?
      				<div>
      					{
      						userInfo.email
      						?
      						<p>您绑定的邮箱是：{userInfo.email}</p>
      						:
      						<p>为确保是您本人进行邮箱绑定，请通过手机校验进行绑定</p>
      					}
								<Verify phone={userInfo.phone} email={userInfo.email}  getIsCodeRight={this.getIsCodeRight.bind(this)}></Verify>
							</div>
							:
							<Form onSubmit={this.handleSubmit.bind(this)}>
				        <Card title="绑定电子邮箱" bordered={false}>
				        	
				        	<Row>
				        		<Col span={16}>
											<FormItem
												{...formItemLayout}
							          label="用户邮箱">
							          {getFieldDecorator('email', {
					            		rules: [{ required: true, message: '请输入您的邮箱地址!' }, { validator: this.checkEmail.bind(this) }],
							            initialValue:this.state.email,
							          })(
							          <Input placeholder="请输入电子邮箱号码" />)}
							        </FormItem>
				        		</Col>
				        	</Row>
				        	<FormItem>
					          <Button
					            type="primary"
					            htmlType="submit"
					            style={{marginLeft: '105px'}}
					          >
					            提交
					          </Button>
					        </FormItem>
				        </Card>
							</Form>
						}
						</Spin>
		      </Col>
				</Row>
			</div>
		)
	}
}
const UpdateEmail = Form.create()(UpdateEmailForm);
export default UpdateEmail;